package exhibition.app.nexd.cn.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import exhibition.app.nexd.cn.R;
import exhibition.app.nexd.cn.application.NexdApplication;
import exhibition.app.nexd.cn.model.Hire;
import exhibition.app.nexd.cn.model.OrderForm;
import exhibition.app.nexd.cn.utils.MD5Util;
import exhibition.app.nexd.cn.utils.Utils;
import exhibition.app.nexd.cn.widget.AddSubPopupWindow;

/**
 * Created by xun on 2016/4/18.
 */
public class HireListAdapter extends BaseAdapter {
    private List<Hire> mHire;
    private LayoutInflater mLayoutInflater;
    private Context mContext;
    private Map<Integer, OrderForm> orderFormMap;

    OnUpdateDataListener onUpdateDataListener;
    private ImageView imgBall;
    private ViewGroup anim_mask_layout;
    private int[] shopCarLocation;
    int[] startLocation = new int[2];

    public void setShopCarLocation(int[] shopCarLocation) {
        this.shopCarLocation = shopCarLocation;
    }

    public HireListAdapter(Context context) {
        this.mHire = NexdApplication.getInstance().getHires();
        this.mContext = context;
        this.mLayoutInflater = LayoutInflater.from(context);
        this.orderFormMap = NexdApplication.getInstance().getOrderFormMap();
    }

    public void setOnUpdateDataListener(OnUpdateDataListener onUpdateDataListener) {
        this.onUpdateDataListener = onUpdateDataListener;
    }

    @Override
    public int getCount() {
        return mHire.size();
    }

    @Override
    public final Hire getItem(int position) {
        return mHire.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.item_hire_list, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.ivAdd.setOnClickListener(new AddOnClickListener(position));
        holder.ivSub.setOnClickListener(new SubOnClickListener(position));
        final Hire hire = getItem(position);
        holder.tvTitle.setText(hire.getTitle());
        holder.tvPrice.setText("￥" + hire.getPrice());
        holder.tvNumber.setVisibility(View.VISIBLE);
        holder.tvDays.setVisibility(View.GONE);
        String redString = "剩余件数:" + hire.getNumber();
        SpannableString redNum = new SpannableString(redString);
        redNum.setSpan(new ForegroundColorSpan(Color.RED), 5, redString.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
        holder.tvNumber.setText(redNum);

        OrderForm orderForm = orderFormMap.get(hire.getHireId());
        if (orderForm != null) {
            if (orderForm.getNum() != 0 && hire.getNumber() != 0) {
                holder.ivSub.setVisibility(View.VISIBLE);
                holder.ivAdd.setVisibility(View.VISIBLE);
                holder.tvOrderNum.setVisibility(View.VISIBLE);
                holder.tvOrderNum.setText(orderForm.getNum() + "");
            } else if (orderForm.getNum() == 0) {
                holder.ivAdd.setVisibility(View.VISIBLE);
                holder.ivSub.setVisibility(View.GONE);
                holder.tvOrderNum.setVisibility(View.GONE);
            } else if (hire.getNumber() == 0) {
                holder.ivAdd.setVisibility(View.GONE);
                holder.ivSub.setVisibility(View.VISIBLE);
                holder.tvOrderNum.setVisibility(View.VISIBLE);
                holder.tvOrderNum.setText(orderForm.getNum() + "");
            }
        } else {
            if (hire.getNumber() == 0) {
                holder.ivAdd.setVisibility(View.GONE);
            } else {
                holder.ivAdd.setVisibility(View.VISIBLE);
            }
            holder.ivSub.setVisibility(View.GONE);
            holder.tvOrderNum.setVisibility(View.GONE);
        }

        if (hire.getDays() != 0) {
            holder.tvNumber.setVisibility(View.GONE);
            holder.tvDays.setVisibility(View.VISIBLE);
            String redDays = "还有" + hire.getDays() + "天才可以租赁";
            SpannableString redDay = new SpannableString(redDays);
            redDay.setSpan(new ForegroundColorSpan(Color.RED), 2, 3, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            holder.tvDays.setText(redDay);
            holder.ivAdd.setVisibility(View.GONE);
            holder.ivSub.setVisibility(View.GONE);
        }
        return convertView;
    }


    // 加号点击事件
    class AddOnClickListener implements View.OnClickListener {

        private int position;

        public AddOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            OrderForm orderForm;
            v.getLocationInWindow(startLocation);
            if (orderFormMap.containsKey(getItem(position).getHireId())) {
                orderForm = orderFormMap.get(getItem(position).getHireId());
            } else {
                orderForm = new OrderForm();
            }
            popupNumWindow(AddSubPopupWindow.TYPE_ADD_NUM, position, orderForm);
        }
    }

    private void popupNumWindow(int type, final int position, final OrderForm orderForm) {
        final AddSubPopupWindow numPopupWindow = new AddSubPopupWindow(mContext);
        numPopupWindow.showAtLocation(((Activity) mContext).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        numPopupWindow.setType(type);
        if (type == AddSubPopupWindow.TYPE_ADD_NUM) {
            numPopupWindow.setItemData(getItem(position).getNumber(), 0);
        } else if (type == AddSubPopupWindow.TYPE_SUB_NUM) {
            numPopupWindow.setItemData(orderForm.getNum(), 0);
        }
        numPopupWindow.setOnSubmitClickListener(new AddSubPopupWindow.OnSubmitClickListener() {
                                                    @Override
                                                    public void onSubmit(int type, String num) {
                                                        int orderNum;
                                                        int hireNum;
                                                        if (type == AddSubPopupWindow.TYPE_ADD_NUM) {
                                                            if (!TextUtils.isEmpty(num))
                                                                if (Integer.parseInt(num) == 0) {
                                                                    Toast.makeText(mContext, "添加物品数量不能为0", Toast.LENGTH_SHORT).show();
                                                                    return;
                                                                }
                                                            if (Integer.parseInt(num) > getItem(position).getNumber()) {
                                                                Toast.makeText(mContext, "库存不足", Toast.LENGTH_SHORT).show();
                                                                return;
                                                            }

                                                            hireNum = getItem(position).getNumber() - Integer.parseInt(num);
                                                            orderNum = orderForm.getNum() + Integer.parseInt(num);// 添加天数
                                                            popupDayWindow(AddSubPopupWindow.TYPE_ADD_DAY, orderForm, position, orderNum, hireNum);
                                                        } else if (type == AddSubPopupWindow.TYPE_SUB_NUM) {
                                                            if (!TextUtils.isEmpty(num) && Integer.parseInt(num) > orderForm.getNum()) {
                                                                Toast.makeText(mContext, "订单中物品不足", Toast.LENGTH_SHORT).show();
                                                                return;
                                                            }
                                                            hireNum = getItem(position).getNumber() + Integer.parseInt(num);
                                                            orderNum = orderForm.getNum() - Integer.parseInt(num);// 添加天数
                                                            popupDayWindow(AddSubPopupWindow.TYPE_SUB_DAY, orderForm, position, orderNum, hireNum);
                                                        }
                                                    }

                                                }

        );
    }

    private void popupDayWindow(int type, final OrderForm orderForm, final int position, final int orderNum, final int hireNum) {
        AddSubPopupWindow dayPopupWindow = new AddSubPopupWindow(mContext);
        dayPopupWindow.showAtLocation(((Activity) mContext).getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        dayPopupWindow.setType(type);
        if (type == AddSubPopupWindow.TYPE_ADD_DAY) {
            dayPopupWindow.setItemData(5, orderForm.getDays());
        } else if (type == AddSubPopupWindow.TYPE_SUB_DAY) {
            dayPopupWindow.setItemData(orderForm.getDays(), 0);
        }
        dayPopupWindow.setOnSubmitClickListener(new AddSubPopupWindow.OnSubmitClickListener() {
            @Override
            public void onSubmit(int type, String num) {
                if (Integer.parseInt(num) == 0) {
                    Toast.makeText(mContext, "添加物品天数不能为0", Toast.LENGTH_SHORT).show();
                    return;
                }
//                if (orderNum == 0) {
//                    //orderFormMap.remove(getItem(position).getHireId());
//                } else {
                orderForm.setOrderFormId(MD5Util.parseStrToMd5L16(System.currentTimeMillis() + NexdApplication.getInstance().getUserId() + ""));
                orderForm.setNum(orderNum);
                orderForm.setUserId(NexdApplication.getInstance().getUserId());
                orderForm.setDays(Integer.parseInt(num));
                orderForm.setHireId(getItem(position).getHireId());
                orderForm.setPrice(getItem(position).getPrice());
                orderForm.setTitle(getItem(position).getTitle());
                orderFormMap.put(getItem(position).getHireId(), orderForm);
//                }
                getItem(position).setNumber(hireNum);
                //声明数组用于存储移动小球的开始动画
                notifyDataSetChanged();
                if (type == AddSubPopupWindow.TYPE_ADD_DAY) {
                    imgBall = new ImageView(mContext);
                    imgBall.setImageResource(R.mipmap.ball);
                    imgBall.setVisibility(View.GONE);
                    setAnim(imgBall, startLocation);
                }
                if (onUpdateDataListener != null) {
                    onUpdateDataListener.onUpdate();
                }
            }
        });
    }

    // 减号点击事件
    class SubOnClickListener implements View.OnClickListener {

        private int position;

        public SubOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            final OrderForm orderForm;
            if (orderFormMap.containsKey(getItem(position).getHireId())) {
                orderForm = orderFormMap.get(getItem(position).getHireId());
            } else {
                orderForm = new OrderForm();
            }
            popupNumWindow(AddSubPopupWindow.TYPE_SUB_NUM, position, orderForm);
        }
    }

    private void setAnim(final ImageView v, int[] startLocation) {
        anim_mask_layout = null;
        anim_mask_layout = createAnimLayout();//创建动画层
        View view = addViewToAnimLayout(anim_mask_layout, v, startLocation);
        int[] endLocation = shopCarLocation;
        //计算位移
        int endX = endLocation[0] - startLocation[0] + Utils.dipToPx(mContext, 25);//动画位移的X坐标
        int endY = endLocation[1] - startLocation[1];
        TranslateAnimation translateAnimationX = new TranslateAnimation(0, endX, 0, 0);
        translateAnimationX.setInterpolator(new LinearInterpolator());//匀速
        translateAnimationX.setRepeatCount(0);//执行一次
        translateAnimationX.setFillAfter(true);

        //y轴动画
        TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0, 0, endY);
        translateAnimationY.setInterpolator(new AccelerateInterpolator());//匀加速
        translateAnimationY.setRepeatCount(0);
        translateAnimationY.setFillAfter(true);
        AnimationSet set = new AnimationSet(false);
        set.setFillAfter(false);
        set.addAnimation(translateAnimationX);
        set.addAnimation(translateAnimationY);
        set.setDuration(800);
        view.startAnimation(set);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                v.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                v.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 将小球放到动画层中,设置放置位置
     *
     * @param anim_mask_layout
     * @param v
     * @param startLocation
     * @return
     */
    private ViewGroup addViewToAnimLayout(ViewGroup anim_mask_layout, ImageView v, int[] startLocation) {
        int x = startLocation[0];
        int y = startLocation[1];
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = x;
        lp.topMargin = y;
        v.setLayoutParams(lp);
        anim_mask_layout.addView(v);
        return anim_mask_layout;
    }

    /**
     * 创建动画图层
     *
     * @return
     */
    private ViewGroup createAnimLayout() {
        //得到当前窗口的顶层布局
        ViewGroup rootView = (ViewGroup) ((Activity) mContext).getWindow().getDecorView();
        LinearLayout animLayout = new LinearLayout(mContext);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        animLayout.setLayoutParams(lp);
        animLayout.setBackgroundResource(android.R.color.transparent);
        rootView.addView(animLayout);
        return animLayout;
    }

    static class ViewHolder {

        @Bind(R.id.hire_tv_title)
        TextView tvTitle;
        @Bind(R.id.hire_tv_number)
        TextView tvNumber;
        @Bind(R.id.hire_tv_item_price)
        TextView tvPrice;
        @Bind(R.id.hire_tv_days)
        TextView tvDays;
        @Bind(R.id.hire_tv_order_num)
        TextView tvOrderNum;
        @Bind(R.id.hire_iv_add)
        ImageView ivAdd;
        @Bind(R.id.hire_iv_sub)
        ImageView ivSub;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    public interface OnUpdateDataListener {
        void onUpdate();
    }


}
